<template>
  <div class="app-container falseTabel-container">
    <div class="customContainer ">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select placeholder="选择品牌" v-model="formInline.brand_id" filterable @change="brandChange">
            <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.is_effective" filterable style="width:100px">
            <el-option v-for="item in effective_list" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formInline.name" placeholder="请输入套餐名称" @keyup.enter.native="searchClick">
          </el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
        <el-button class="pull-right" type="primary" size="small" @click="addEditClick()">新增充值套餐</el-button>
      </el-form>
      <!-- 表格 -->
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="small">
        <el-table-column align="center" label='套餐名称' prop="name" width="210px"></el-table-column>
        <el-table-column align="center" label='充值金额' width="100px">
          <template slot-scope="scope">
            <p v-for="item in scope.row.rule.limit" :key="item">{{item}}</p>
          </template>
        </el-table-column>
        <el-table-column align="center" label='获得币数' width="100px">
          <template slot-scope="scope">
            <p v-for="item in scope.row.rule.give" :key="item">{{item}}</p>
          </template>
        </el-table-column>
        <el-table-column align="center" label='适用等级' prop="card_type_name" :render-header="(h,obj) => renderHeader(h,obj,'同一门店同一等级相同时间段内优先级最高的套餐生效')">
        </el-table-column>
        <el-table-column align="center" label='套餐优先级' prop="priority"></el-table-column>
        <el-table-column align="center" label='生效时间'>
          <template slot-scope="scope">
            {{scope.row.effect_time+' - '+scope.row.stop_time}}
          </template>
        </el-table-column>
        <el-table-column align="center" label='操作' width="220px">
          <template slot-scope="scope">
            <el-button @click="addEditClick(scope.row.id,scope.$index)" type="primary" icon="el-icon-edit" size="mini"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delPackageClick(scope.row.id,scope.$index)"></el-button>
            <el-button type="primary" plain size="mini" @click="deployStoreClick(scope.row.id)">配置门店
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 新增编辑弹框 -->
      <el-dialog :close-on-click-modal="false" style="width:-80px" id="selectStyle_parent" width="515px" :title="dialogTitle" :visible.sync="addEditDialog"
        append-to-body @close="callOf">
        <div style="height:550px;overflow:auto;">
          <el-form :model="saveForm" ref="saveForm" :inline="true" class="demo-form-inline">
            <el-form-item label="套餐名称　" required>
              <el-input :maxlength="15" onkeypress="return event.which!=32" placeholder="请输入套餐名称(十五字内)" v-model="saveForm.name" style="width:350px;"></el-input>
            </el-form-item>
            <el-form-item label="适用等级　" required>
              <el-select v-model="saveForm.card_type_id" multiple placeholder="请选择" style="width:350px;" @change="gradeChange">
                <el-option v-for="item in card_type_list" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="套餐优先级" required>
              <el-input onkeypress="return event.which>=48&&event.which<=57" type="number" onmousewheel="return false;" min="0" v-model="saveForm.priority"
                placeholder="输1-999正整数" style="width:130px"></el-input>
              <span class="indexColor">优先级范围1~999，1为优先级最高</span>
            </el-form-item>
            <el-form-item label="生效日期　" required>
              <el-date-picker :editable="false" :clearable="false" v-model="saveForm.pickerDate" value-format="yyyy-MM-dd" type="daterange" align="right"
                unlink-panels range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
            </el-form-item>
            <el-form-item label="充值规则　" required>
              <el-table highlight-current-row :data="saveForm.rules" v-loading.body="listLoading" border size="small">
                <el-table-column align="center" label='序号' width="48">
                  <template slot-scope="scope">
                    <span class="indexColor">{{scope.$index+1}}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label='充值金额 ' width="155">
                  <template slot-scope="scope">
                    <el-input size="small" onkeypress="return event.which>=48&&event.which<=57" type="number" onmousewheel="return false;" min="0"
                      v-model="scope.row.limit" placeholder="输入正整数"></el-input>
                  </template>
                </el-table-column>
                <el-table-column align="center" label='获得币数' width="155">
                  <template slot-scope="scope">
                    <el-input size="small" onkeypress="return event.which>=48&&event.which<=57" type="number" onmousewheel="return false;" min="0"
                      v-model="scope.row.give" placeholder="输入正整数"></el-input>
                  </template>
                </el-table-column>
                <el-table-column align="center" label='操作'>
                  <template slot-scope="scope">
                    <el-button @click="delClick(scope.$index)" type="danger" icon="el-icon-delete" size="mini"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <p style="border:1px solid #dedede;text-align:center" v-if="isEdit&&saveForm.rules.length<10">
                <el-button type="text" @click="addRuleClick">新增规则
                  <i class="el-icon-circle-plus-outline"></i>
                </el-button>
              </p>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="savePackageClick" size="small"> 保 存 </el-button>
        </div>
      </el-dialog>
      <!-- 配置门店弹框 -->
      <el-dialog :close-on-click-modal="false" width="650px" title="选择门店" :visible.sync="storeDialog">
        <div>
          <div class="el-transfer-panel pull-left transferHeader">选择门店</div>
          <div class="el-transfer-panel pull-right transferHeader">已选门店</div>
        </div>
        <el-transfer :props="{key: 'id', label: 'name'}" :titles="['全选', '全选']" :button-texts="['删除', '添加']" filterable v-model="check_store_list"
          :data="storeList">
        </el-transfer>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" type="primary" @click="saveStoreClick">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
        layout="prev, pager, next, jumper" :total="totalDataNumber">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getList,
  getPage,
  get_check_store_list,
  addPackage,
  editPackage,
  delPackage,
  savePackage,
  getStoreList,
  getBrandList,
  saveStore
  // getGrade
} from '@/api/member/member_package';
import { pickerOptionsAfterF, renderHeader } from '@/utils';
import $ from 'jquery';
export default {
  data() {
    return {
      renderHeader,
      card_type_list: [{ id: '0', name: '普通会员卡' }, { id: '1', name: '精英会员卡' }, { id: '2', name: '临时卡' }],
      effective_list: [{ id: '1', name: '有效套餐' }, { id: '0', name: '失效套餐' }],
      storeDialog: false,
      isCreateDom: true,
      list: null,
      listLoading: false,
      addEditDialog: false,
      isDisabled: true,
      storeList: null,
      brandList: null,
      editIndex: '',
      isEdit: false,
      currentPage: 1,
      check_store_list: [],
      url: '',
      dialogTitle: '',
      totalDataNumber: 1,
      formInline: {
        type: 0,
        name: '',
        brand_id: '',
        is_effective: '1'
      },
      saveStore: {
        id: '',
        store_list: []
      },
      saveForm: {
        brand_id: '',
        pickerDate: [],
        priority: '',
        effect_time: '',
        stop_time: '',
        id: '',
        name: '',
        rules: [],
        type: 0,
        card_type_id: []
      },
      pickerOptions: pickerOptionsAfterF()
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.brandList) {
        vm.getBrand();
      }
    });
  },
  methods: {
    deployStoreClick(id) {
      get_check_store_list({ id: id }).then(response => {
        this.check_store_list = response;
      });
      this.saveStore.id = id;
      this.storeDialog = true;
    },
    saveStoreClick() {
      this.saveStore.store_list = this.check_store_list;
      saveStore(this.saveStore).then(response => {
        this.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message });
        this.storeDialog = false;
      });
    },
    delClick(index) {
      if (this.saveForm.rules.length == 1) {
        this.saveForm.rules[index].limit = '';
        this.saveForm.rules[index].give = '';
      } else {
        this.saveForm.rules.splice(index, 1);
      }
    },
    addRuleClick() {
      this.saveForm.rules.push({ limit: '', give: '' });
    },
    getBrand() {
      getBrandList({ org: 1, category_id: 253 }).then(response => {
        this.brandList = response;
        this.formInline.brand_id = response[0].id;
        this.brandChange();
        if (this.list == null) {
          this.fetchData();
        }
      });
    },
    brandChange() {
      this.getStore();
    },
    getStore() {
      getStoreList({ brand: this.formInline.brand_id, category_id: 253 }).then(response => {
        this.storeList = response;
      });
    },
    gradeChange() {
      if (this.saveForm.card_type_id.length == this.card_type_list.length) {
        $('.allCheck').prop('checked', true);
      } else {
        $('.allCheck').prop('checked', false);
      }
    },
    addEditClick(id, index) { 
      this.check_store_list = [];
      this.dialogTitle = id ? '修改充值套餐' : '新增充值套餐';
      this.addEditDialog = true;
      this.editIndex = id ? index : '';
      this.isEdit = id ? false : true;
      this.url = id ? '/Operations_recharge_package/edit_recharge_package' : '/Operations_recharge_package/create_recharge_package';
      this.saveForm.id = id ? id : '';
      this.saveForm.name = id ? this.list[index].name : '';
      this.saveForm.priority = id ? this.list[index].priority : '';
      this.saveForm.pickerDate = id ? [this.list[index].effect_time, this.list[index].stop_time] : [];
      this.saveForm.card_type_id = id ? this.list[index].card_type_id.split(',') : [];
      this.saveForm.rules = id ? this.list[index].rules : [{ limit: '', give: '' }];
      if (this.isCreateDom) {
        setTimeout(() => {
          $('#selectStyle_parent .el-scrollbar__view').prepend(
            "<label><li class='el-select-dropdown__item noHover' ><input class='allCheck' type='checkbox'/> 全选</li></label>"
          );
          $('#selectStyle_parent .allCheck').on('click', () => {
            if ($('.allCheck').is(':checked')) {
              this.saveForm.card_type_id = [];
              this.card_type_list.forEach(val => {
                this.saveForm.card_type_id.push(val.id);
              });
            } else {
              this.saveForm.card_type_id = [];
            }
          });
          this.gradeChange();
          this.isCreateDom = false;
        }, 0);
      }
      this.gradeChange();
    },
    savePackageClick() {
      let ok = true;
      if (this.saveForm.name == '' || this.saveForm.priority == '' || this.saveForm.card_type_id.length == 0 || this.saveForm.pickerDate.length == 0) {
        this.$message({ type: 'error', message: '请将信息填写完整' });
        ok = false;
        return;
      }
      if (!/^\+?[1-9]\d{0,2}(\.\d*)?$/.test(this.saveForm.priority)) {
        this.$message({ type: 'error', message: '优先级范围1~999整数' });
        ok = false;
        return;
      }
      if (this.saveForm.rules) {
        this.saveForm.rules.forEach(val => {
          if (val.limit * 1 <= 0 || val.give * 1 <= 0 || val.give * 1 > 999999 || val.give * 1 > 999999) {
            this.$message({ type: 'error', message: '请填写完整充值规则，并且是只能为小于999999的正整数' });
            ok = false;
            return false;
          }
        });
      }
      if (ok) {
        this.saveForm.brand_id = this.formInline.brand_id;
        this.saveForm.effect_time = this.saveForm.pickerDate[0];
        this.saveForm.stop_time = this.saveForm.pickerDate[1];
        let data = JSON.parse(JSON.stringify(this.saveForm));
        savePackage(data, this.url).then(response => {
          this.addEditDialog = false;
          this.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message });
        });
      }
    },
    delPackageClick(id, index) {
      this.$confirm('确认删除(当升级条件发生变化后,用户不降级)', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        delPackage({ id: id }).then(response => {
          this.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message });
          if (response.code == 1) {
            this.list.splice(index, 1);
          }
        });
      });
    },
    callOf() {
      this.handleCurrentChange(this.currentPage);
    },
    // 搜索
    searchClick() {
      this.fetchData();
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      this.currentPage = 1;
      getPage(this.formInline)
        .then(response => {
          this.totalDataNumber = response * 20;
          getList(this.formInline).then(response => {
            this.list = response;
            this.listLoading = false;
          });
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    // 分页
    handleCurrentChange(val) {
      this.listLoading = true;
      getList(this.formInline, val).then(response => {
        this.list = response;
        this.listLoading = false;
      });
    }
  }
};
</script> 